/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-05-29
 * Time: 20:00
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
            return null;
        }

        ListNode pa = headA;
        ListNode pb = headB;
        int i = 0, j = 0;
        while(pa != null){
            pa = pa.next;
            i++;
        }
        while(pb != null){
            pb = pb.next;
            j++;
        }

        if(i > j){
            int k = i - j;
            while(k > 0){
                headA = headA.next;
                k--;
            }
        } else {
            int k = j - i;
            while(k > 0){
                headB = headB.next;
                k--;
            }
        }

        while(headA != null && headB != null){
            if(headA == headB){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }

        return null;
    }


}
